package broker

import (
	"errors"
	"fmt"
	"hft/Database/admin"
	"hft/Http/Models/dao"
	resFront "hft/Http/Models/response/front"
	utils "hft/Http/Utils"
	"hft/global"
	"hft/tools"
	"time"

	"gorm.io/gorm"
)

// 领取客户
type GetUser struct{}

func (*GetUser) GetUserToBroker(userId int, claims tools.BaseClaims) (err error) {

	var account *admin.Account

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).Preload("AccountExpand").First(&account).Error

	if err != nil {
		return (errors.New("无该经纪人信息"))
	}

	var user *admin.User

	err = global.OC_DB.Preload("ClueList", func(db *gorm.DB) *gorm.DB {
		return db.Order("create_time desc")
	}).First(&user, userId).Error

	if err != nil {
		return (errors.New("无该用户信息"))
	}

	// 获取经纪人所属位置
	city, _ := utils.GetRegionBelongCity(account.RegionLink)

	if city != int(user.City) {
		return errors.New("你无法获取该城市客户")
	}

	// 获取所需金币
	var citySet *admin.CitySetting

	err = global.OC_DB.Where("region = ?", city).First(&citySet).Error

	if err != nil {
		return errors.New("该城市尚未加盟")
	}

	var need_gold uint

	if user.ClueList[0].LouPanId == 0 {
		need_gold = citySet.CommonClueScore
	} else {
		need_gold = citySet.LouPanClueScore
	}

	if int(account.AccountExpand.Score-need_gold) < 0 {
		return errors.New("你的房币不足")
	}

	res := global.OC_DB.Model(&admin.User{}).Where("id = ? AND now_broker_id = ?", user.ID, 0).Updates(map[string]interface{}{
		"now_broker_id": account.ID,
		"broker_name":   account.RealName,
		"broker_time":   time.Now(),
		"broker_num":    user.BrokerNum + 1,
	})

	global.OC_DB.Model(&admin.AccountExpand{}).Where("account_id = ?", account.ID).Update("score", account.AccountExpand.Score-need_gold)

	if res.RowsAffected != 1 {
		return (errors.New(fmt.Sprintf("该客户已被领取%v", account.ID)))
	}

	return nil
}

// 公客池
func (*GetUser) GetGlobalUser(paginate *utils.Page, claims tools.BaseClaims) (page *utils.Page, err error) {

	var account *admin.Account

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	fmt.Println(tools.JsonParse(account))

	// 找出负责的楼盘
	var lou []*admin.LouPan
	global.OC_DB.Model(&account).Association("LouPan").Find(&lou)
	// 找出无人接管的楼盘
	var louWu []*admin.LouPan
	global.OC_DB.Raw("SELECT`hft_loupans`.`id`,`hft_loupans`.`name`,`hft_account_lou_pan`.`account_id` FROM`hft_loupans`LEFT JOIN `hft_account_lou_pan` ON `hft_loupans`.`id` = `hft_account_lou_pan`.`lou_pan_id`WHERE`hft_account_lou_pan`.`account_id` IS NULL").Scan(&louWu)
	var newLou = append(lou, louWu...)
	var ids = make([]int, 0)
	for _, v := range newLou {
		ids = append(ids, int(v.ID))
	}

	// 获取经纪人所属位置
	city, _ := utils.GetRegionBelongCity(account.RegionLink)

	fmt.Println(city)

	var user []*resFront.GetUserPage
	global.OC_DB.Model(&admin.Clue{}).Select(
		"`hft_clue`.`id`,`hft_clue`.`user_id`,`hft_user`.`create_time`,`hft_user`.`update_time`, `hft_user`.`deleted_at`,`hft_user`.`valid`,`hft_user`.`now_broker_id`,`hft_user`.`city`,`hft_clue`.`page_name`,`hft_clue`.`lou_pan_id`,`hft_clue`.`activity_name`,`hft_clue`.`origin_name`,`hft_user`.`phone`,`hft_clue`.`belong_name`",
	).Joins("left join `hft_user` on `hft_clue`.`user_id` = `hft_user`.`id`").Where("lou_pan_id IN ?", append(ids, 0)).Where("now_broker_id = ?", 0).Where("`hft_user`.`city` = ?", city).Order("`hft_user`.`update_time` desc").Group("user_id").Scopes(dao.Paginate(dao.Page(*paginate), global.OC_DB)).Find(&user).Scopes(dao.GetCount(global.OC_DB)).Count(&paginate.Total)

	for _, v := range user {
		v.Phone = utils.DesensitizePhoneNumber(v.Phone)
	}

	paginate.Data = user

	return paginate, nil

}

// 查看公客池的客户资料
func (*GetUser) GetGlobalUserInfo(id uint, claims tools.BaseClaims) (userInfo *resFront.GlobalUserInfo, err error) {

	var account *admin.Account

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	if err != nil {
		return nil, errors.New("未知错误500")
	}
	// 获取经纪人所属位置
	city, _ := utils.GetRegionBelongCity(account.RegionLink)

	var user *admin.User

	err = global.OC_DB.Where("now_broker_id = ?", 0).Preload("ClueList", func(db *gorm.DB) *gorm.DB {
		return db.Order("create_time desc")
	}).First(&user, id).Error

	if err != nil {
		return nil, errors.New("该客户已被领取")
	}

	// 获取当前城市的城市设置
	var citySet *admin.CitySetting

	err = global.OC_DB.Where("region = ?", city).First(&citySet).Error

	if err != nil {
		return nil, errors.New("该城市尚未加盟")
	}

	var gold uint

	if user.ClueList[0].LouPanId == 0 {
		gold = citySet.CommonClueScore
	} else {
		gold = citySet.LouPanClueScore
	}

	var is_new_customer bool

	if user.BrokerNum == 0 {
		is_new_customer = true
	} else {
		is_new_customer = false
	}

	var protect_day float32

	switch user.Level {
	case "A":
		protect_day = citySet.LevelA
	case "B":
		protect_day = citySet.LevelB
	case "C":
		protect_day = citySet.LevelC
	case "D":
		protect_day = citySet.LevelD
	}

	var newUser = &resFront.GlobalUserInfo{
		ID:            user.ID,
		CreateTime:    user.CreateTime,
		UpdateTime:    user.UpdateTime,
		Phone:         utils.DesensitizePhoneNumber(user.Phone),
		PageName:      user.ClueList[0].PageName,
		OriginName:    user.ClueList[0].OriginName,
		ActivityName:  user.ClueList[0].ActivityName,
		Level:         user.Level,
		Valid:         user.Valid,
		NeedGold:      gold,
		IsNewCustomer: is_new_customer,
		ProtectDay:    protect_day,
	}

	return newUser, nil

}

// 获取私客池
func GetPrivatePool(claims tools.BaseClaims) (list []*admin.User, err error) {

	var account *admin.Account

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	if err != nil {
		return nil, errors.New("无改用户信息")
	}

	var user []*admin.User

	err = global.OC_DB.Where("now_broker_id = ?", account.ID).Find(&user).Error

	return user, err

}

// 获取私客详情
func (*GetUser) GetPrivateUserInfo(id uint, claims tools.BaseClaims) (userInfo *resFront.GlobalUserInfo, err error) {

	var account *admin.Account

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	if err != nil {
		return nil, errors.New("未知错误500")
	}
	// 获取经纪人所属位置
	city, _ := utils.GetRegionBelongCity(account.RegionLink)

	var user *admin.User

	err = global.OC_DB.Where("now_broker_id = ?", account.ID).Preload("ClueList", func(db *gorm.DB) *gorm.DB {
		return db.Order("create_time desc")
	}).First(&user, id).Error

	if err != nil {
		return nil, errors.New("该客户不存在")
	}

	// 获取当前城市的城市设置
	var citySet *admin.CitySetting

	err = global.OC_DB.Where("region = ?", city).First(&citySet).Error

	if err != nil {
		return nil, errors.New("该城市尚未加盟")
	}

	var gold uint

	if user.ClueList[0].LouPanId == 0 {
		gold = citySet.CommonClueScore
	} else {
		gold = citySet.LouPanClueScore
	}

	var is_new_customer bool

	if user.BrokerNum == 0 {
		is_new_customer = true
	} else {
		is_new_customer = false
	}

	var protect_day float32

	switch user.Level {
	case "A":
		protect_day = citySet.LevelA
	case "B":
		protect_day = citySet.LevelB
	case "C":
		protect_day = citySet.LevelC
	case "D":
		protect_day = citySet.LevelD
	}

	var newUser = &resFront.GlobalUserInfo{
		ID:            user.ID,
		CreateTime:    user.CreateTime,
		UpdateTime:    user.UpdateTime,
		Phone:         utils.DesensitizePhoneNumber(user.Phone),
		PageName:      user.ClueList[0].PageName,
		OriginName:    user.ClueList[0].OriginName,
		ActivityName:  user.ClueList[0].ActivityName,
		Level:         user.Level,
		Valid:         user.Valid,
		NeedGold:      gold,
		IsNewCustomer: is_new_customer,
		ProtectDay:    protect_day,
	}

	return newUser, nil

}

var GetUserService = new(GetUser)
